package com.think.utils;

import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.util.Map;
import java.util.Properties;

public class YamlUtils {
    private static final Logger logger = LoggerFactory.getLogger("error");

    public static Map<String, Object> yaml2Map(String yamlSource) {
        try {
            YamlMapFactoryBean yaml = new YamlMapFactoryBean();
            yaml.setResources(new ClassPathResource(yamlSource));
            return yaml.getObject();
        } catch (Exception e) {
            logger.error("Cannot read yaml", e);
            return null;
        }
    }

    public static Properties yaml2Properties(String yamlSource) {
        try {
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            yaml.setResources(new ClassPathResource(yamlSource));
            return yaml.getObject();
        } catch (Exception e) {
            logger.error("Cannot read yaml", e);
            return null;
        }
    }

    public static void main(String[] args) {
        Map<String, Object> map = YamlUtils.yaml2Map("application.yml");
        Properties prop = YamlUtils.yaml2Properties("application.yml");
        Assert.assertNotNull(map);
        map.forEach((k, v) -> {
            logger.info("k={},v={}", k, v);
        });
        Assert.assertNotNull(prop);
        prop.forEach((k, v) -> logger.info("k={},v={}", k, v));
    }
}
